/*
 * DBQuery.java
 *
 * Created on 11. Mai 2007, 15:52
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.googlecode.oskis.library.db;
import java.sql.*;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
        
/**
 * DBQuery führt eine SQL Abfrage auf der Datenbank aus und füllt das <br>
 * Ergebnis in ein DefaultTableModel
 * @author dicth
 */
public class DBQuery {
    
    private Connection db;
    private Statement st;
    private ResultSet rs;
    
    private int resultColumns;
    private int resultRows;
    
    private DefaultTableModel tm;
    
    private String SQL;
    private String SQLError;
    
    /** DBQuery Objekt erzeugen, nur DB Connection, SQL Statement wird sp�ter gesetzt */
    public DBQuery(Connection db) {
        this.db=db;
    }
    
    /** DBQuery Objekt erzeugen */
    public DBQuery(Connection db,String SQL) {
        this.db=db;
        this.SQL=SQL;
    }
    
    public String getSQLError() {
        return(SQLError);
    }
    
    /** DB Connect auf andere Datenbank setzen */
    public void setConnection(Connection db) {
        this.db=db;
    }
    
    public Connection getConnection() {
        return(this.db);
    }
   
    public void setStatement(String SQL) {
        this.SQL=SQL;
    }
    
    public String getStatement() {
        return(SQL);
    }
    
    public boolean executeQuery() {
        Vector columnNames;
        try {
            st=db.createStatement();
            rs=st.executeQuery(SQL);
            resultColumns=rs.getMetaData().getColumnCount();            
            columnNames=new Vector(resultColumns);
            for (int i=1;i<=resultColumns;i++) {
                columnNames.addElement(rs.getMetaData().getColumnName(i));
            }
            tm=new DefaultTableModel(columnNames,0);
            resultRows=0;
            while (rs.next()) {
                Vector row=new Vector(resultColumns);
                for (int i=1;i<=resultColumns;i++) {
                    row.addElement(rs.getString(i));
                }
                tm.addRow(row);
                resultRows++;
            }
            SQLError="";
            rs.close();
            st.close();
            return(true);
        } catch (SQLException e) {
            System.err.println(e);
            SQLError=e.toString();
            return(false);
        }
    }
    
    public boolean executeQuery(String SQL) {
        this.SQL=SQL;
        return(executeQuery());
    }
    
    public DefaultTableModel getTableModel() {
        return(tm);
    }
    
    public ResultSet getResultSet() {
        return(rs);
    }
    
    public int getRowCount() {
        return(resultRows);
    }
    
    public void printResult() {
        
    }
}
